//console.log("----------------hello")

var initData = {};
//所有页面的数据
var allDataList = [];
//默认当前为第一页
var currentPage = 1;
//需要解密到的最后一页
var lastPage=1;

var timeStamp = new Date().getTime();

String.prototype.myReplace=function(f,e){//吧f替换成e
    var reg=new RegExp(f,"g"); //创建正则RegExp对象   
    return this.replace(reg,e); 
}

//计算是多少天之前的订单
function  getDaysBetween(dateString1){
   var  startDate = Date.parse(dateString1);
   var days=(timeStamp - startDate)/(1*24*60*60*1000);
   // alert(days);
   return  days;
}


function getInitData() {
    $.ajax({
        type: "get",
        url:
            "https://fxg.jinritemai.com/common/index/index?_" + timeStamp,
        dataType: "json",
        success: function (res) {
			//debugger;
            initData = res.data;
        },
    });
}
getInitData();

async function Sleep(sleepSecs) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve()
        }, sleepSecs * 1000)
    })
}

//直到conditionFunc执行成功
async function WaitUntil(conditionFunc, sleepSecs) {
    sleepSecs = sleepSecs || 1;
    return new Promise((resolve, reject) => {
  //       if (conditionFunc()){
		// 	console.log("验证成功");
		// 	clearInterval(interval)
		// 	resolve();
		// }else{
			
			let interval = setInterval(() => {
			    if (conditionFunc()) {
					// console.log("验证成功")
			        clearInterval(interval)
			        resolve()
			    }else{
					// console.log("等待验证")
				}
			}, sleepSecs * 1000)
		// }
        
    })
}


//生成一个在min到max之间的随机数
function randomNum(min, max){
	var Range = max - min;
	var Rand = Math.random();
	return (parseInt(Math.round(Rand * Range),10) + parseInt(min, 10));
}


//获取随机数组
function RegroupArr(arr) {
	if (arr.length <= 1) return arr;
	var backupArr = [].concat(arr); //备份原来的数组，后面的操作会对数组进行修改
	var result = [];
	var r = randomNum(0,backupArr.length - 1); //生成0到length-1之间的随机数
	result = result.concat(backupArr.splice(r, 1)); //从原来的数组中删除随机数位置的数字并存到结果中
	result = result.concat(RegroupArr(backupArr)); //回调本函数，对删除随机数后剩下的数组进行排序
	return result;
}



// GM_xmlhttpRequest
function Request(url, opt={}) {
	Object.assign(opt, {
		url,
		timeout: 2000,
		responseType: 'json'
	})

	return new Promise((resolve, reject) => {
		/*
		for (let f of ['onerror', 'ontimeout'])
			opt[f] = reject
		*/

		opt.onerror = opt.ontimeout = reject
		opt.onload = resolve

        // console.log('Request', opt)

		GM_xmlhttpRequest(opt)
	}).then(res => {
        if (res.status === 200) return Promise.resolve(res.response)
        else return Promise.reject(res)
    }, err => {
        return Promise.reject(err)
    })
}

function Get(url, opt={}) {
    Object.assign(opt, {
        method: 'GET'
    })
    return Request(url, opt)
}

function Post(url, opt={}) {
    Object.assign(opt, {
        method: 'POST'
    })
    return Request(url, opt)
}

async function getShopName() {
    await WaitUntil(() => {
        return !!document.querySelector('div.headerShopName')
    })

    return document.querySelector('div.headerShopName').innerText
}

function toCsvString(headers, dataList) {
    let rows = []
    rows.push(headers)
    for (let d of dataList) {
        let row = []
        for (let h of headers) {
            row.push(d[h])
        }
        rows.push(row)
    }
    rows = rows.map(row => {
        return row.map(s => `"${s}"`).join(',')
    }).join('\n')
    return 'data:text/csv;charset=utf-8,\ufeff' + rows
}

function extractOrderDiv(div) { // 将div里的内容搞成object
    let resp = {}
    let header = div.querySelector('div[class^="index_rowHeader"] > div[class^="index_RowHeader"] > div[class^="index_leftWrapper"]')
    let spanList = header.querySelectorAll('span')
    if (spanList.length >= 1) {
        // console.log(spanList[0].innerText)
        resp.orderId = '	' + spanList[0].innerText.match(/订单号\s*(\d+)/)[1]
    }
    if (spanList.length >= 2) {
        // console.log(spanList[1].innerText)
        resp.orderTime = spanList[1].innerText.match(/下单时间\s*([\d\/ :]+)/)[1]
    }
    // if (spanList.length >= 3) {
    //     // console.log(spanList[1].innerText)
    //     resp.sourceType = spanList[2].innerText.match(/推广类型：\s*(.*)/)[1]
    // }

    // content
    // let content = div.querySelector('div:nth-of-type(2)')
    let content = div.querySelector('div[class^="index_rowHeader"]').nextSibling
    let product = content.querySelector('div[class^="style_productItem"] > div[class^="style_content"]')
    //resp.image = product.querySelector('img').getAttribute('src')
    resp.title = product.querySelector('div[class^="style_detail"] > div[class^="style_name"]').innerText
	//console.log(resp.title);
	
	//名称下面的信息,sku
	//resp.sku = product.querySelector('div[class^="style_property"] > div[class^="style_desc"]').innerText
	let skuList = product.querySelectorAll('div[class^="style_property"] > div[class^="style_desc"]')
	resp.sku = Array();
	for(let i=0;i<skuList.length;i++){
		console.log(skuList[i].innerText)
		resp.sku[i] = skuList[i].innerText
	}

    resp.unitPrice = content.querySelector('div[class^="index_cellRow"] > div[class^="index_cell"]:nth-of-type(2) > div[class^="table_comboAmount"]').innerText
    resp.number = content.querySelector('div[class^="index_cellRow"] > div[class^="index_cell"]:nth-of-type(2) > div[class^="table_comboNum"]').innerText

    resp.payAmount = content.querySelector('div[class^="index_payAmount"]').innerText

    resp.nickname = content.querySelector('a[class^="table_nickname"]').innerText
	resp.nickname = resp.nickname.myReplace('#','-')
	//联系人，联系地址
    resp.contact = content.querySelector('div[class^="index_locationDetail"]').innerText
	resp.contact = resp.contact.myReplace('#','-')
	
    let contactList = resp.contact.split("\n")
    if (contactList.length >= 3) {
        resp.contactName = contactList[0]
        resp.contactPhone = contactList[1]
        resp.contactAddress = contactList[2]
    }

    resp.status = div.querySelector('div:nth-of-type(2) > div[class^="index_cell"]:nth-of-type(4) > div:first-of-type').innerText
	
    return resp
}


//收集页面数据
function collectCurrentData(){
	//查找包含数据的div
	let divList = document.querySelectorAll('div.auxo-spin-container > div:nth-of-type(2) > div > div[data-kora_order_status]')
	let dataList = []
	
	for (let div of divList) {
		//将div中的数据构造成Object
	    let data = extractOrderDiv(div)
	    // console.log(data)
	    dataList.push(data)
	}
	//将本页数据放入全局变量
	allDataList.push.apply(allDataList,dataList);
}

async function downloadData() {
    let headers = ['orderId', 'orderTime', 'title', 'sku', 'unitPrice', 'number', 'payAmount', 'nickname', 'contactName', 'contactPhone', 'contactAddress', 'contact', 'status'];// 'sourceType','image'
    const csvString = toCsvString(headers, allDataList)
    // console.log('csvString', csvString)

    let shopName = await getShopName()

    let link = document.createElement('a')
    link.setAttribute('href', csvString)
    let filename = `${shopName}-订单`
    link.setAttribute('download', filename + '.csv')
    link.click()
}

async function addDownloadButton() {
    await WaitUntil(() => {
        return !!document.querySelector('div[class^="index_middle-bar-wrapper"] div[class^="index_batchOpWrap"] div[class^="index_buttonGroup"]')
    })

    let div = document.querySelector('div[class^="index_middle-bar-wrapper"] div[class^="index_batchOpWrap"] div[class^="index_buttonGroup"]')
    let btn = div.querySelector('button').cloneNode(true)
    btn.setAttribute('data-id', '下载订单')
    btn.setAttribute('_cid', 'export-orders')
    btn.innerHTML = `<span>下载订单</span>`
    div.appendChild(btn)

    btn.onclick = (e) => {
        console.log('btn.onclick', e)
		collectCurrentData()
        downloadData()
    }
}

//解密并下载
async function decodeCurrentPage() {
    $viewsAll = $("[data-kora='view']"); //眼睛DOM
	
	//去掉已关闭的，因为已关闭的订单，不允许查看
	var $views=[];
	$viewsAll.each(function(i){
		//包含订单号，下单时间的那一行
		let header = $(this).closest('div[class^="index_tableRow"]').find('div[class^="index_rowHeader"] > div[class^="index_RowHeader"] > div[class^="index_leftWrapper"]')
		let spanList = header.find('span')
		let orderTime = spanList[1].innerText.match(/下单时间\s*([\d\/ :]+)/)[1]
		
		let days = getDaysBetween(orderTime)
		// console.log(days)
		//状态不是已关闭，并且是36天之内的订单
		if("已关闭" != $(this).closest('div[class^="index_cell"]').next().text() && days<36){
			$views.push($(this));
		}else{
			// console.log("排除已关闭订单");
		}
	});
	
	  /*
	//生成一个随机数组,用于设置每个订单界面的时间点
	var arr = [];
	for (let i = 1; i <= ($views.length*2); i++) {
		arr.push(i);
	}
	var randomArr = RegroupArr(arr);
	//截取数组前*个
	var usedRandomArr = randomArr.slice(0,$views.length);
	console.log(randomArr)
	console.log(usedRandomArr)
*/

/*
	if($views.length > 0){
		//点击第一个小眼睛
		console.log(`正在解密第 1条订单`);
		tip(`正在解密第 1 条订单`);
		$($views[0]).trigger("click");
		
		//验证是否有弹出校验的框,等待直到验证框消失
		await WaitUntil(() => {
			
			return !document.querySelector('.captcha_verify_container')
		})
		console.log("验证通过");
	}
	*/
   
   //解密正式开始
	for (let i = 0; i < $views.length; i++) {
		
		/*
		(function(t) { // 注意这里是形参
			setTimeout(function() {
				console.log(`正在解密第 ${t+1} 条订单`);
				tip(`正在解密第 ${t+1} 条订单`);
				$($views[t]).trigger("click");
				
				//验证是否有弹出校验的框,等待直到验证框消失
				await WaitUntil(() => {
				    return !document.querySelector('.captcha_verify_container')
				})
				
			}, usedRandomArr[t]*1200);
		})(i) // 注意这里是实参，这里把要用的参数传进去
		*/
	   
	   
		await new Promise((resolve, reject) => {
		  setTimeout(() => {
			// console.log(`正在解密第 ${i+1} 条订单`);
			tip(`正在解密第 ${i+1} 条订单`);
			$($views[i]).trigger("click");
						
			resolve();
		  }, randomNum(5,7)*1100);
		  // }, 500);
		})
		
	   
		//验证是否有弹出校验的框,等待直到验证框消失
		await WaitUntil(() => {
			return !document.querySelector('.captcha_verify_container,.ant-modal')
		})
		// console.log("验证通过");
	}
	

/*
	//最后那个小眼睛点击的时间
	// var lastTime = Math.max(...usedRandomArr)*1200;
	// console.log("最大的数:"+lastTime);
	
	//        	//收集本页数据
	//        	collectCurrentData();
	//        	resolve();
	//        	//显示完自动下载下载
	//        	// tip('已全部解密完成，开始下载...');
	//        	// downloadData();
	*/
   
	// (
	//   async () => {
		  //2秒后，收集本页数据
		await new Promise((resolve, reject) => {
		  setTimeout(() => {
			//收集本页数据
			// console.log("正在收集本页数据");
			//tip("正在收集本页数据");
			collectCurrentData();
			resolve();
		  },2000);
		})
		
		//如果没到设置的最后一页，则继续请求下一页
		if(currentPage < lastPage){
			//1秒后，点击下一页
			await new Promise((resolve, reject) => {
			  setTimeout(() => {
				jumpPage(++currentPage);
				resolve();
			  }, 1000);
			})

		}else{
			setTimeout(() => {
				// console.log("正在导出订单");
				tip("正在导出订单");
				downloadData();
			}, 1000);
			
		}
		
	//   }
	// )();
	  
}


//添加显示按钮
async function addShowButton() {
	//不断检测，直到找到出现相关代码
    await WaitUntil(() => {
        return !!document.querySelector('div[class^="index_middle-bar-wrapper"] div[class^="index_batchOpWrap"] div[class^="index_buttonGroup"]')
    })

    let div = document.querySelector('div[class^="index_middle-bar-wrapper"] div[class^="index_batchOpWrap"] div[class^="index_buttonGroup"]')
    let btn = div.querySelector('button').cloneNode(true)
    btn.setAttribute('data-id', '解密订单')
    btn.setAttribute('_cid', 'decode-orders')
    btn.innerHTML = `<span>解密订单</span>`
    div.appendChild(btn)

    btn.onclick = (e) => {
        // console.log('btn.onclick', e)
		checkPermission();
    }
}

//跳转到currentPage
var Ts;
function jumpPage(){
	$("[rel='nofollow']").each(function(){
		if(parseInt($(this).text()) == currentPage ){
			//console.log("正在跳转至第"+currentPage+"页");
			tip("正在跳转至第"+currentPage+"页");
			$(this)[0].click();
			//每秒轮询，检查是否加载完成
			Ts = window.setInterval(checkLoading, 1000 * 1);
		}
	});
	
}
//轮询检测下一页是否加载完
function checkLoading() {
	//没有等待遮盖层的css，代表页面加载结束
	if($(".auxo-spin-blur").length <= 0){
		//结束轮询
		window.clearInterval(Ts);
		
		setTimeout(() => {
			//显示并收集本页订单数据
			decodeCurrentPage();
		},1000);
		
	}
}

function checkPermission(callback) {
	// 发送消息
	chrome.runtime.sendMessage({
	    info: "checkPermission",
		param:"shopId="+initData.toutiao_id+"&shopName="+initData.shop_name
	}, res => {})
	
}

// 接收消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
	let jsonData = $.parseJSON( request );
	if (!jsonData.code) {
		//被拒
		poplayer.msg(jsonData.msg);
	} else {
		if("success" != jsonData.msg){
			poplayer.msg(jsonData.msg);
		}
		
		poplayer.prompt1('请输入要解密的页码','确定','取消','您输入的页码错误！',true,'1','1',function(data1,data2){
			document.body.removeChild(document.getElementById("pop_tip")); // 关闭上一个弹层
			//poplayer.msg('获取到输入的值：'+data1+"-"+data2);
			//开始页
			currentPage = data1;
			//结束页
			lastPage = data2;
			//跳转页面并收集
			jumpPage();
			
			// collectCurrentData();
			// downloadData();
			//decodeCurrentPage();
			
		})
		
	}
	
	sendResponse('success');
});

//test
async function addTestButton() {
    await WaitUntil(() => {
        return !!document.querySelector('div[class^="index_middle-bar-wrapper"] div[class^="index_batchOpWrap"] div[class^="index_buttonGroup"]')
    })

    let div = document.querySelector('div[class^="index_middle-bar-wrapper"] div[class^="index_batchOpWrap"] div[class^="index_buttonGroup"]')
    let btn = div.querySelector('button').cloneNode(true)
    btn.setAttribute('data-id', 'test')
    btn.setAttribute('_cid', 'test-orders')
    btn.innerHTML = `<span>test</span>`
    div.appendChild(btn)

    btn.onclick = (e) => {
        // console.log('btn.onclick', e)
        test()
		// checkPermission(test);
    }
}

function test(){
	poplayer.prompt1('请输入要解密的页码','确定','取消','页码是必填项',true,'1','1',function(data1,data2){
		document.body.removeChild(document.getElementById("pop_tip")); // 关闭上一个弹层
		poplayer.msg('获取到输入的值：'+data1+"-"+data2);
	});
}

(async function() {
    'use strict';

    // Your code here...
    await addShowButton()
    //await addDownloadButton()
    //await addTestButton()
})();

var tipCount = 0;
// 简单的消息通知
function tip(info) {
	info = info || '';
	var ele = document.createElement('div');
	ele.className = 'chrome-plugin-simple-tip slideInLeft';
	ele.style.bottom = tipCount * 70 + 20 + 'px';
	ele.innerHTML = `<div>${info}</div>`;
	document.body.appendChild(ele);
	ele.classList.add('animated');
	tipCount++;
	setTimeout(() => {
		ele.style.bottom = '-100px';
		setTimeout(() => {
			ele.remove();
			tipCount--;
		}, 400);
	}, 3000);
}



